from PySide6.QtWidgets import QWidget, QLabel, QVBoxLayout
from PySide6.QtCore import Qt, QTimer, QPoint
from PySide6.QtGui import QScreen, QGuiApplication

# 添加全局变量来存储 Toast 实例
_toast_instance = None

class Toast(QWidget):
    """
    自定义轻量级提示框
    """
    def __init__(self, text, parent=None, duration=2000):
        super().__init__(parent)
        # 设置无边框窗口
        self.setWindowFlags(
            Qt.FramelessWindowHint |  # 无边框
            Qt.Tool |                 # 工具窗口
            Qt.WindowStaysOnTopHint  # 置顶窗口
        )
        # 设置背景透明
        self.setAttribute(Qt.WA_TranslucentBackground)
        
        # 创建布局
        layout = QVBoxLayout()
        layout.setContentsMargins(10, 5, 10, 5)
        
        # 创建标签
        self.label = QLabel(text)
        self.label.setStyleSheet("""
            QLabel {
                color: black;
                font-weight: bold;
                background-color: white;
                border: 1px solid #ddd;
                border-radius: 4px;
                padding: 8px;
                font-size: 13px;
                box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            }
        """)
        self.label.setAlignment(Qt.AlignCenter)
        layout.addWidget(self.label)
        self.setLayout(layout)
        
        # 设置定时器自动关闭
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.close)
        self.timer.start(duration)
        
        # 显示在右下角
        self.show_at_right_bottom()
        
    def show_at_right_bottom(self):
        """显示在屏幕右下角"""
        screen = QGuiApplication.primaryScreen().availableGeometry()
        size = self.sizeHint()
        x = screen.width() - size.width() - 20  # 右边距离20像素
        y = screen.height() - size.height() - 40  # 下边距离40像素
        self.move(x, y)
        self.show()

def show_toast(text, duration=2000):
    """
    显示一个Toast提示
    Args:
        text: 提示文本
        duration: 显示时长(毫秒)
    """
    global _toast_instance
    # 如果已经有正在显示的 toast，先关闭它
    if _toast_instance is not None:
        _toast_instance.close()
    
    _toast_instance = Toast(text, duration=duration)
    return _toast_instance 